package com.flink.wc;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
 * @author mark
 * @date 2021/12/31 18:05
 */
public class WorkCount {
    public static void main(String[] args) throws Exception{
        //创建执行环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
        //从上下文读取数据
        DataSource<String> readTextFile = env.readTextFile("G:\\gitee\\mq\\flink\\src\\main\\resources\\hello.txt");

        //对数据集进行处理,按空格分词转换成(word ,1)进行统计
        final AggregateOperator<Tuple2<String, Integer>> sum = readTextFile.flatMap(new MyFlatMapper())
                // 按照第一个位置word分组
                .groupBy(0)
                //将第二个位置的数据求和
                .sum(1);
        sum.print();
    }

    /**
     * 自定义类，实现FlatMapFunction接口
     */
    public static class MyFlatMapper implements FlatMapFunction<String, Tuple2<String, Integer>>{

        private static final long serialVersionUID = 2393054714922100302L;

        @Override
        public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
            // 空格分词
            String[] words = value.split(" ");
            // 遍历所有word，包含二元组输出
            for (String word : words){
                out.collect(new Tuple2<>(word, 1));
            }

        }
    }
}
